package com.wjw.rabbitdemo.service;

import com.rabbitmq.client.Channel;
import com.wjw.rabbitdemo.entity.OrderEntity;
import com.wjw.rabbitdemo.entity.RabbitReturnEntity;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
//@RabbitListener标在类上，@RabbitHandler区分收到的消息
@RabbitListener(queues = {"hello-java-QueueDemo"})
public class ReceiveService {
    //必须在容器里 queues = {声明需要监听的所有队列}
    //Message 头+体
    //@RabbitListener(queues = {"hello-java-QueueDemo"})
    public void receiveMessage(Message message, RabbitReturnEntity rabbitReturnEntity, Channel channel){
        //获取收到的消息体
        byte[] body=message.getBody();
        //获取消息头属性消息
        MessageProperties messageProperties=message.getMessageProperties();
        System.out.println("接受到消息："+rabbitReturnEntity);
    }
    //ack自动模式，如果只有一个消息处理成功，服务器宕机会的话，会发生消息丢失
    //spring.rabbitmq.listener.simple.acknowledge-mode=manual设置手动确认后，没有ack，消息就会在unacked状态等待
    @RabbitHandler
    public void receiveRabbitReturnPojo(Message message,RabbitReturnEntity rabbitReturnEntity,Channel channel){
        System.out.println("接受到消息："+rabbitReturnEntity);

        long deliverTag=message.getMessageProperties().getDeliveryTag();
        //手动确认收货 deliverTag当前消息的数字标签，自增 multiple是否批量接受消息
        try {
            channel.basicAck(deliverTag,false);
            System.out.println("签收货物"+deliverTag);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @RabbitHandler
    public void receiveRabbitReturnPojo(OrderEntity orderEntity,Channel channel){
        System.out.println("接受到消息："+orderEntity);
    }
}
